package ru.linnenson.darshana.infrastructure.ocr;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.stereotype.Service;
import ru.linnenson.darshana.application.services.PhotoReader;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Service
@RequiredArgsConstructor
public class TesseractService implements PhotoReader {

  private final Tesseract tesseract;

  @Override
  public String read(final byte[] photo) {

    try {

      final InputStream stream = new ByteArrayInputStream(photo);
      final BufferedImage image = ImageIO.read(stream);

      stream.close();

      return tesseract.doOCR(image).replaceAll("\n", " ");

    } catch (TesseractException | IOException e) {

      log.error("OCR failed: ", e);

      return "";
    }
  }
}
